package com.fingard.crypto;

import com.fingard.text.StringHelper;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class CertHelper {

    /**
     * 获取公钥转16进制字符串返回
     */
    public static String getPublicKeyAsHexStr(String p_ksType, String p_ksPath, String p_kPass, StringBuilder p_sbLog) {
        byte[] retBytes = new byte[0];
        try {
            retBytes = getPublicKey(p_ksType, p_ksPath, p_kPass, p_sbLog);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (retBytes != null) {
            return StringHelper.bytesToHexString(retBytes);
        }
        return null;
    }

    /**
     * 获取公钥
     */
    public static byte[] getPublicKey(String p_ksType, String p_ksPath, String p_kPass, StringBuilder p_sbLog) throws IOException {
        FileInputStream fis = null;
        try {
            KeyStore ks = KeyStore.getInstance(p_ksType);//"PKCS12"
            fis = new FileInputStream(p_ksPath);
            char[] keyPassword = null;
            if (StringHelper.hasAnyChar(p_kPass)) {
                keyPassword = p_kPass.toCharArray();
            }
            ks.load(fis, keyPassword);
            fis.close();
            fis = null;
            @SuppressWarnings("rawtypes")
            Enumeration enumAlias = ks.aliases();
            String keyAlias = null;
            if (enumAlias.hasMoreElements()) {
                keyAlias = (String) enumAlias.nextElement();
            }
            Certificate cer = ks.getCertificate(keyAlias);
            return cer.getEncoded();
        } catch (Exception ex) {
            p_sbLog.append(ex.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception ex) {
                    p_sbLog.append(ex.getMessage());
                }
            }
        }
        return null;
    }
}
